import React, { useState, useEffect } from 'react';
import { Shield, Server, CheckCircle, AlertTriangle, XCircle, RefreshCw } from 'lucide-react';
import { monitorApi } from '../../services/monitor';
import type { ClusterHealthMetrics } from '../../types/monitor';

interface ClusterHealthMonitorProps {
  refreshInterval?: number;
}

const ClusterHealthMonitor: React.FC<ClusterHealthMonitorProps> = ({
  refreshInterval = 30000
}) => {
  const [loading, setLoading] = useState(false);
  const [healthMetrics, setHealthMetrics] = useState<ClusterHealthMetrics | null>(null);
  const [error, setError] = useState<string | null>(null);

  // 获取集群健康状态
  const fetchClusterHealth = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await monitorApi.getClusterHealth();
      if (response.success) {
        setHealthMetrics(response.data);
      }
    } catch (error) {
      console.error('获取集群健康状态失败:', error);
      setError('获取集群健康状态失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchClusterHealth();
    const interval = setInterval(fetchClusterHealth, refreshInterval);
    return () => clearInterval(interval);
  }, [refreshInterval]);

  // 获取健康状态颜色和图标
  const getHealthStatus = (health: string) => {
    switch (health.toLowerCase()) {
      case 'healthy':
        return { 
          color: 'text-green-500', 
          bgColor: 'bg-green-100', 
          icon: CheckCircle, 
          text: '健康' 
        };
      case 'warning':
        return { 
          color: 'text-yellow-500', 
          bgColor: 'bg-yellow-100', 
          icon: AlertTriangle, 
          text: '警告' 
        };
      case 'critical':
        return { 
          color: 'text-red-500', 
          bgColor: 'bg-red-100', 
          icon: XCircle, 
          text: '严重' 
        };
      default:
        return { 
          color: 'text-gray-500', 
          bgColor: 'bg-gray-100', 
          icon: AlertTriangle, 
          text: '未知' 
        };
    }
  };

  // 计算健康分数
  const calculateHealthScore = () => {
    if (!healthMetrics) return 0;
    
    let score = 100;
    if (healthMetrics.under_replicated_partitions > 0) {
      score -= Math.min(healthMetrics.under_replicated_partitions * 5, 40);
    }
    if (healthMetrics.issues.length > 0) {
      score -= Math.min(healthMetrics.issues.length * 10, 50);
    }
    return Math.max(score, 0);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
        <span className="ml-2">加载中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex items-center">
          <AlertTriangle className="w-5 h-5 text-red-500 mr-2" />
          <span className="text-red-700">{error}</span>
        </div>
      </div>
    );
  }

  if (!healthMetrics) {
    return (
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
        <div className="text-center text-gray-500">暂无数据</div>
      </div>
    );
  }

  const healthStatus = getHealthStatus(healthMetrics.overall_health);
  const healthScore = calculateHealthScore();
  const HealthIcon = healthStatus.icon;

  return (
    <div className="space-y-6">
      {/* 集群健康概览 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <div className="flex items-center">
            <HealthIcon className={`w-8 h-8 ${healthStatus.color} mr-3`} />
            <div>
              <p className="text-sm font-medium text-gray-600">集群状态</p>
              <p className={`text-2xl font-bold ${healthStatus.color}`}>
                {healthStatus.text}
              </p>
            </div>
          </div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <div className="flex items-center">
            <Server className="w-8 h-8 text-blue-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">Broker数量</p>
              <p className="text-2xl font-bold text-gray-900">{healthMetrics.broker_count}</p>
            </div>
          </div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <div className="flex items-center">
            <AlertTriangle className="w-8 h-8 text-yellow-500 mr-3" />
            <div>
              <p className="text-sm font-medium text-gray-600">副本不足分区</p>
              <p className={`text-2xl font-bold ${
                healthMetrics.under_replicated_partitions > 0 ? 'text-red-500' : 'text-green-500'
              }`}>
                {healthMetrics.under_replicated_partitions}
              </p>
            </div>
          </div>
        </div>
        
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <div className="flex items-center">
            <RefreshCw 
              className={`w-8 h-8 text-blue-500 mr-3 cursor-pointer ${loading ? 'animate-spin' : ''}`}
              onClick={fetchClusterHealth}
            />
            <div>
              <p className="text-sm font-medium text-gray-600">刷新</p>
              <p className="text-sm text-gray-500">点击刷新数据</p>
            </div>
          </div>
        </div>
      </div>

      {/* 健康分数和问题列表 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 健康分数 */}
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">集群健康分数</h3>
          <div className="flex items-center justify-center">
            <div className="relative w-32 h-32">
              <svg className="w-32 h-32 transform -rotate-90" viewBox="0 0 36 36">
                <path
                  className="text-gray-300"
                  stroke="currentColor"
                  strokeWidth="3"
                  fill="none"
                  d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                />
                <path
                  className={
                    healthScore >= 80 ? 'text-green-500' : 
                    healthScore >= 60 ? 'text-yellow-500' : 'text-red-500'
                  }
                  stroke="currentColor"
                  strokeWidth="3"
                  strokeLinecap="round"
                  fill="none"
                  strokeDasharray={`${healthScore}, 100`}
                  d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                />
              </svg>
              <div className="absolute inset-0 flex items-center justify-center">
                <span className={`text-2xl font-bold ${
                  healthScore >= 80 ? 'text-green-500' : 
                  healthScore >= 60 ? 'text-yellow-500' : 'text-red-500'
                }`}>
                  {healthScore.toFixed(0)}
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* 问题列表 */}
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            集群问题 
            {healthMetrics.issues.length > 0 && (
              <span className="ml-2 px-2 py-1 text-xs bg-red-100 text-red-800 rounded-full">
                {healthMetrics.issues.length}
              </span>
            )}
          </h3>
          {healthMetrics.issues.length === 0 ? (
            <div className="flex items-center text-green-600">
              <CheckCircle className="w-5 h-5 mr-2" />
              <span>集群运行正常，无问题发现</span>
            </div>
          ) : (
            <div className="space-y-2 max-h-40 overflow-y-auto">
              {healthMetrics.issues.map((issue, index) => (
                <div key={index} className="flex items-start">
                  <AlertTriangle className="w-4 h-4 text-yellow-500 mr-2 mt-0.5 flex-shrink-0" />
                  <span className="text-sm text-gray-700">{issue}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Broker详情 */}
      <div className="bg-white rounded-lg shadow-sm border">
        <div className="px-6 py-4 border-b border-gray-200">
          <h3 className="text-lg font-medium text-gray-900">Broker详情</h3>
        </div>
        <div className="p-6">
          {Object.keys(healthMetrics.brokers).length === 0 ? (
            <div className="text-center text-gray-500 py-8">暂无Broker信息</div>
          ) : (
            <div className="space-y-4">
              {Object.entries(healthMetrics.brokers).map(([brokerId, brokerData]) => (
                <div key={brokerId} className="border border-gray-200 rounded-lg p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center">
                      <Server className="w-5 h-5 text-gray-400 mr-2" />
                      <span className="font-medium">Broker {brokerData.broker_id}</span>
                      {brokerData.is_controller && (
                        <span className="ml-2 px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
                          控制器
                        </span>
                      )}
                      <span className={`ml-2 px-2 py-1 text-xs rounded-full ${
                        brokerData.is_available ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                      }`}>
                        {brokerData.is_available ? '在线' : '离线'}
                      </span>
                    </div>
                    <div className="flex items-center space-x-4 text-sm text-gray-500">
                      <span>主机: {brokerData.host}:{brokerData.port}</span>
                      {brokerData.rack && <span>机架: {brokerData.rack}</span>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ClusterHealthMonitor;
